package org.yixiu.consumer;

import lombok.extern.slf4j.Slf4j;
import org.yixiu.producer.entity.RpcRequest;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * 客户端动态代理对象处理器
 */
@Slf4j
public class ConsumerInvocationHandler implements InvocationHandler {

    private String host;
    private int port;

    public ConsumerInvocationHandler(String host, int port) {
        this.host = host;
        this.port = port;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        try(Socket socket = new Socket(host,port);
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream())
        ){
            RpcRequest rpcRequest = RpcRequest.builder()
                    .interfaceName(method.getDeclaringClass().getName())
                    .methodName(method.getName())
                    .paramTypes(method.getParameterTypes())
                    .params(args)
                    .build();
            outputStream.writeObject(rpcRequest);
            Object result = inputStream.readObject();
            log.info("Consumer output: " + result);
            return result;
        }catch (Exception e){
           log.info("consumer invoke method error",e);
           throw new RuntimeException(e.getMessage());
        }
    }
}
